import cv2
import numpy as np
from fastapi import HTTPException
from app.config.settings import settings


def validate_image_size(content: bytes):
    if len(content) > settings.max_image_size:
        raise HTTPException(
            status_code=413,
            detail=f"Image size exceeds limit {settings.max_image_size} bytes"
        )


def bytes_to_cvimage(file_content: bytes) -> np.ndarray:
    try:
        np_array = np.frombuffer(file_content, np.uint8)
        image = cv2.imdecode(np_array, cv2.IMREAD_COLOR)
        if image is None:
            raise ValueError("Invalid image format")
        return image
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))
